package com.sise.aio和bio和nio.nio.基于nio的多人聊天室;


import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;

/**
 * @author idea
 * @data 2019/1/20
 */
public class NioServer {

    public static void main(String[] args) throws IOException {

        ServerSocketChannel sschannel = ServerSocketChannel.open();

        //非堵塞模式
        sschannel.configureBlocking(false);

        sschannel.bind(new InetSocketAddress(9999));

        //获取选择器
        Selector selector = Selector.open();

        //将通道注册到选择器上边，并且监听socket的接受事件
        sschannel.register(selector, SelectionKey.OP_ACCEPT);

        while (selector.select() > 0) {
            //将所有的选择器key进行轮询
            Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
            while (iterator.hasNext()) {
                SelectionKey selectionKey = iterator.next();
                //如果当前选择器的key为接受套接字类型的话
                if (selectionKey.isAcceptable()) {
                    SocketChannel socketChannel = sschannel.accept();
                    socketChannel.configureBlocking(false);
                    socketChannel.register(selector, SelectionKey.OP_READ);
                } else if (selectionKey.isReadable()) {
                    SocketChannel socketChannel = (SocketChannel) selectionKey.channel();
                    ByteBuffer byteBuffer = ByteBuffer.allocate(1024);

                    int len = 0;
                    while ((len = (socketChannel.read(byteBuffer))) > 0) {
                        byteBuffer.flip();
                        System.out.println(new String(byteBuffer.array(), 0, len));
                        byteBuffer.clear();
                    }
                }
                //取消选择键
                iterator.remove();
            }
        }

    }
}
